﻿namespace CatClient.Message.Internals
{
    using CatClient;
    using CatClient.Message;
    using CatClient.Message.Spi;
    using System;

    [Serializable]
    public class DefaultForkedTransaction : DefaultTransaction, IForkedTransaction, ITransaction, IMessage
    {
        private string _rootMessageId;
        private string _parentMessageId;
        private string _forkedMessageId;

        public DefaultForkedTransaction(string type, string name, IMessageManager messageManager) : base(type, name, messageManager)
        {
            base.Standalone = false;
            IMessageTree threadLocalMessageTree = messageManager.ThreadLocalMessageTree;
            if (threadLocalMessageTree != null)
            {
                this._rootMessageId = threadLocalMessageTree.RootMessageId;
                this._parentMessageId = threadLocalMessageTree.MessageId;
                this._forkedMessageId = Cat.CreateMessageId();
            }
        }

        public void Fork()
        {
            string contextKey = Guid.NewGuid().ToString();
            IMessageManager messageManager = base.MessageManager;
            messageManager.Setup(contextKey);
            messageManager.Start(this, false);
            base._contextKey = contextKey;
            IMessageTree threadLocalMessageTree = messageManager.ThreadLocalMessageTree;
            if (threadLocalMessageTree != null)
            {
                threadLocalMessageTree.MessageId = this._forkedMessageId;
                threadLocalMessageTree.RootMessageId = this._rootMessageId ?? this._parentMessageId;
                threadLocalMessageTree.ParentMessageId = this._parentMessageId;
            }
        }

        public string ForkedMessageId =>
            this._forkedMessageId;
    }
}

